package org.enhance.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.enhance.common.exception.EnhanceRuntimeException;

/**
 * @author JiangGengchao
 * @classname StringUtil
 * @date 2021-10-29
 **/
public class StringUtil {

	private StringUtil() {
		throw new IllegalStateException("Constant class");
	}

	public static String removeIllegalStr(String name) {
		if (StringUtils.isNotBlank(name)) {
			String[] strs = { "/", "\\\\", "?", "*", "[", "]", ":" };
			name = StringUtil.remove(name, strs);
		}
		return name;
	}

	/**
	 * 获取随机字符串
	 *
	 * @param num
	 * @return
	 */
	public static String getRandomNum(Integer num) {
		String base = "0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < num; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static String remove(String str, String[] removes) {
		if (org.apache.commons.lang3.StringUtils.isBlank(str) || removes == null || removes.length == 0) {
			return str;
		}

		for (String remove : removes) {
			str = StringUtils.remove(str, remove);
		}
		return str;
	}

	public static String getRandomString(Integer num) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < num; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static String getUUID() {
		String s = UUID.randomUUID().toString();
		// 去掉“-”符号
		return s.replaceAll("-", "");
	}

	public static String getUrlPath(String url) {
		try {
			URL urlObject = new URL(url);
			return urlObject.getPath();
		} catch (Exception e) {
			throw new EnhanceRuntimeException(e);
		}
	}

	public static String getUrlEncode(String ecodeStr) {
		try {
			return URLEncoder.encode(ecodeStr, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new EnhanceRuntimeException(e);
		}
	}
}